package com.honvay.hdms.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.filter.TokenFilter;
import com.honvay.hdms.auth.core.AuthenticatedUser;
import com.honvay.hdms.department.domain.Department;
import com.honvay.hdms.department.mapper.DepartmentMapper;
import com.honvay.hdms.dms.document.entity.Document;
import com.honvay.hdms.dms.document.repository.DocumentRepository;
import com.honvay.hdms.user.domain.User;
import com.honvay.hdms.user.mapper.UserMapper;
import com.honvay.hdms.utils.CacheManager;
import com.honvay.hdms.utils.CurrentUserBinder;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


/**
 * 跨域配置
 */
@Component
public class WebFilter implements Filter {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    private String[] noFilterUrl = {"/user/login","/fs/upload", "/fs/download"};
//
//    @Value("${token.expireTime}")
//    private long expireTime;

    private final String tokenName = "x-token";

    private final String terminalId = "tid";

    @Autowired
    private com.honvay.hdms.department.mapper.DepartmentMapper departmentMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //log.info("----------------过滤器初始化------------------------");
    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        settCors(request, response);
        //如果是OPTIONS请求就return 往后执行会到业务代码中 他不带参数会产生异常
        if (request.getMethod().equals("OPTIONS")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if (isInclude(request.getServletPath(), noFilterUrl)) {
            //白名单不拦截
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            String token = request.getHeader(tokenName);
            String s = CacheManager.get(token);
            User userSource = JSONObject.parseObject(s, User.class);
            AuthenticatedUser user = new AuthenticatedUser();
            BeanUtils.copyProperties(userSource, user);
            user.setMountId(2);// 选择企业空间
            Department department1 = departmentMapper.selectById(user.getDepartmentId());
            user.setDepartment(department1);
            CurrentUserBinder.bindUser(JSON.toJSONString(user));
            filterChain.doFilter(servletRequest, servletResponse);
        }
        return;
//            String token = "";
//            String terminalId = getTerminalId(request);
//            if (StrUtil.isEmpty(terminalId)) {
//                //判断是否为空
//                responseOutWithJson(response, R.error(HttpStatus.UNAUTHORIZED.value(), "接入端为空"));
//                return;
//            }
//            token = request.getHeader(tokenName);
//            if (StrUtil.isNotEmpty(token)) {
//                String key = RedisKeyUtil.getRedisKey(RedisKey.LOGIN_TOKEN, terminalId, token);
//                if (cacheUtil.hasKey(key)) {
//                    String userInfo = (String) cacheUtil.get(key);
//                    long liveTime = cacheUtil.getExpire(key);
//                    if (liveTime < expireTime) {
//                        // 更新过期时间
//                        cacheUtil.expire(key, Const.TOKEN_EXPIRE_SECONDS);
//                    }
//                    CurrentUserBinder.bindUser(userInfo);
//                    filterChain.doFilter(servletRequest, servletResponse);
//                } else {
//                    responseOutWithJson(response, R.error(HttpStatus.UNAUTHORIZED.value(), "验权失败"));
//                }
//            } else {
//                responseOutWithJson(response, R.error(HttpStatus.UNAUTHORIZED.value(), "验权失败"));
//            }
//            return;
//        }
    }

    private String getTerminalId(HttpServletRequest request) {
        String terminalId = request.getHeader(this.terminalId);
        if (terminalId == null) {
            terminalId = request.getParameter(this.terminalId);
        }
        return terminalId;
    }


    @Override
    public void destroy() {

        // log.info("--------------过滤器销毁--------------");
    }

    /**
     * 是否需要过滤
     *
     * @param url
     * @return
     */
    private boolean isInclude(String url, String[] targetUrl) {
        for (String pattern : targetUrl) {
            if (url.indexOf(pattern) != -1) {
                return true;
            }
        }
        return false;
    }

    /**
     * 以JSON格式输出
     *
     * @param response
     */
    private void responseOutWithJson(HttpServletResponse response,
                                     Object responseObject) {
        //将实体对象转换为JSON Object转换
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(JSONObject.toJSONString(responseObject));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    private void settCors(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header,x-token");
        //添加请求头 给前端获取文件流名称
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Access-Control-Allow-Credentials", "true");
    }
}
